package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @description: 用户注册接口
 * @author: enhui
 **/
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Reference(timeout = 3000, check = false)
    IKaptchaService kaptchaService;
    @Reference(timeout = 3000, check = false)
    IRegisterService registerService;

    /**
     * 用户注册，需要验证输入的验证码，需要cookie中的携带的参数，入参需要request
     *
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest request) {
        //拿到请求参数
        String email = map.get("email");
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");

        //注册，插入数据：用户表、用户验证表、发送用户激活邮件

        //1.验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        //从cookie中取出这个uuid，Cookie: SameSite=None; kaptcha_uuid=a28f4b6f-ea8c-47c7-8331-afb536391c1b
        String kaptchaUuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptchaUuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse codeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!codeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            //验证失败
            return new ResponseUtil().setErrorMsg(codeResponse.getMsg());
        }
        //验证成功继续

        //2.向表中插入记录
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        registerRequest.setEmail(email);
        UserRegisterResponse response = registerService.register(registerRequest);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            //成功
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
